import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.PriorityQueue;

public class Congress {

	public static void main(String[] args) {
		new Congress();
	}

	private String inputFileUri = "C:/Users/Michell/Downloads/congress/ex/huge-200000.in"; // Set the URI of the input file
	private String outputFileUri = "C:/Users/Michell/Downloads/congress/ex/result-huge-200000.out"; // Set the URI of the output file
	
	private int numberOfSeats, numberOfStates;
	private PriorityQueue<State> priorityQueue;

	public Congress() {
		try {
			FileInputStream fileinput = new FileInputStream(inputFileUri);
			BufferedReader reader = new BufferedReader(new InputStreamReader(fileinput, "UTF8"));

			numberOfStates = Integer.parseInt(reader.readLine());
			numberOfSeats = Integer.parseInt(reader.readLine());

			if (numberOfStates > numberOfSeats) {
				System.out.println("Not enough seats to give each state one seat!");
				return;
			}

			priorityQueue = new PriorityQueue<State>();

			String line = "", line2 = "";
			while ((line = reader.readLine()) != null && (line2 = reader.readLine()) != null) {
				// Go through all the states defined in the text file and give each a seat (which happens in the State constructor)
				priorityQueue.add(new State(line, Integer.parseInt(line2)));
				numberOfSeats--;
			}

			// Give the remaining seats to the states based on priority
			State s;
			int size = numberOfSeats;
			for (int i = 0; i < size; i++) {
				s = priorityQueue.remove();
				s.addSeat();
				priorityQueue.add(s);
			}

			// Write the results to the output file
			FileWriter fw = new FileWriter(outputFileUri);
			BufferedWriter bw = new BufferedWriter(fw);
			
			for (State state : priorityQueue) {
				bw.write(state.print() + "\n");
			}
			
			bw.close();

		} catch (UnsupportedEncodingException e) { 	System.out.println("Unsupported encoding! The input file must be in UTF-8 encoding!");
		} catch (FileNotFoundException e) { 		System.out.println("File not found. Check the URI of the FileInputStream.");
		} catch (IOException e) { 					System.out.println("Couldn't access the file.");
		}
	}
}